package cn.woblog.android.downloader.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import android.os.Environment;
import cn.woblog.android.downloader.exception.ObtainFileSizeException;

public class FileUtils {

	private static boolean interrupte;

	public static void setInterrupteObtainFileSize(boolean isInterrupte) {
		FileUtils.interrupte = isInterrupte;
	}

	public static boolean getInterrupteObtainFileSize() {
		return FileUtils.interrupte;
	}

	public static String downloadFile(String url, String path) {
		try {
			HttpURLConnection connection = getHttpUrlConnection(false, url, 0,
					0);
			InputStream is = connection.getInputStream();
			FileOutputStream os = new FileOutputStream(path);

			byte[] buffer = new byte[4096];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				os.write(buffer, 0, len);
			}
			is.close();
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return path;
	}

	public static HttpURLConnection getHttpUrlConnection(boolean isRange,
			String url, long startPos, long endPos)
			throws MalformedURLException, IOException, ProtocolException {
		URL urls = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) urls
				.openConnection();
		connection.setRequestMethod("GET");
		connection.setConnectTimeout(Consts.CONNECT_TIMEOUT);
		connection.setReadTimeout(Consts.READ_TIMEOUT);
		if (isRange) {
			connection.addRequestProperty("Range", "bytes=" + startPos + "-"
					+ endPos);
		}
		return connection;
	}

	// public static LinkedList<Part> parseM3u8(DownloadData entry) {
	// LinkedList<Part> parts = new LinkedList<Part>();
	// // LinkedHashMap<String, Part> parts = new LinkedHashMap<String,
	// // Part>();
	// try {
	// // File file = new File(entry.getBasePath());
	// // if (!file.exists()) {
	// // file.mkdirs();
	// // }
	// FileInputStream fis = new FileInputStream(entry.getBasePath()
	// + entry.getName());
	// InputStreamReader isr = new InputStreamReader(fis);
	// BufferedReader br = new BufferedReader(isr);
	// String line = null;
	// long size = 0;
	// long totulSize = 0;
	// while ((line = br.readLine()) != null) {
	// if (interrupte) {
	// break;
	// }
	// if (!TextUtils.isEmpty(line)) {
	// if (line.indexOf("#EXT-X-KEY") != -1) {
	// downloadM3u8Key(entry, line);
	// } else if (line.indexOf(".ts") != -1) {
	// size = getFileSize(entry.getBashUrl() + line);
	// totulSize += size;
	// Part part = new Part(line, size);
	// Logs.d("obtain file size:" + entry.getBashUrl() + line
	// + ":" + size);
	// parts.add(part);
	// }
	// }
	// }
	// if (interrupte) {
	// entry.setSize(0);
	// } else {
	// entry.setSize(totulSize);
	// }
	//
	// br.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// } catch (ObtainFileSizeException e) {
	// e.printStackTrace();
	// }
	// return parts;
	// }
	//
	// private static void downloadM3u8Key(DownloadData entry, String line) {
	// int lastIndexOf = line.lastIndexOf("http");
	// if (lastIndexOf != -1) {
	// String keyUrl = line.subSequence(lastIndexOf, line.length() - 1)
	// .toString();
	// Logs.d("keyUrl:" + keyUrl);
	// int indexof = keyUrl.lastIndexOf("/");
	// if (indexof != -1) {
	// String keyName = keyUrl.substring(indexof + 1);
	// Logs.d("keyName:" + keyName);
	// String keyPaht = downloadFile(keyUrl, entry.getPath() + "/"
	// + keyName);
	// }
	// }
	// }
	//
	public static long getFileSize(String path) throws ObtainFileSizeException {
		try {
			BasicHttpParams httpParameters = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParameters,
					Consts.CONNECT_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParameters,
					Consts.READ_TIMEOUT);
			HttpGet getMethod = new HttpGet(path);
			HttpClient httpClient = new DefaultHttpClient();
			HttpResponse response = httpClient.execute(getMethod);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				long contentLength = response.getEntity().getContentLength();
				// Logs.d("contentLength:" + contentLength);
				return contentLength;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new ObtainFileSizeException("obtain file" + path + "faild", e);
		}
		throw new ObtainFileSizeException("obtain file" + path + "faild");
	}

	// public static DownloadData getDownloadEntry(VideoData videoData, int uid,
	// int parentId, String parentName) {
	// File file = new File(DownloadData.downloadPath + uid + "/" + parentId
	// + "/");
	// if (!file.exists()) {
	// file.mkdirs();
	// }
	// String videoUrl = videoData.getVideoUrl();
	// int lastIndexOf = videoUrl.lastIndexOf(".");
	// int lastIndex = videoUrl.lastIndexOf("/");
	// String suffix = "";
	// String name = videoData.getVideoId() + "";
	// if (lastIndexOf != -1) {
	// int lastIndexOf2 = videoUrl.lastIndexOf("?");
	// if (lastIndexOf2 == -1) {
	// lastIndexOf2 = videoUrl.length();
	// }
	// suffix = videoUrl.substring(lastIndexOf, lastIndexOf2);
	// name = videoUrl.substring(lastIndex + 1, lastIndexOf2);
	// }
	// String saveBasePath = file.getAbsolutePath() + "/";
	// DownloadData data;
	// if (videoData.getVideoUrl().lastIndexOf("m3u8") != -1) {
	// data = new DownloadData(videoData.getVideoUrl(), saveBasePath,
	// saveBasePath + name);
	// } else {
	// data = new DownloadData(videoData.getVideoUrl(), saveBasePath,
	// saveBasePath + videoData.getId() + suffix);
	// }
	//
	// data.setName(name);
	// data.setDisplayName(videoData.getVideoName());
	// data.setWatchDuration(videoData.getWatchDuration());
	// data.setVideoDuration(videoData.getVideoDuration());
	// data.setParentId(parentId);
	// data.setParentName(parentName);
	// data.setcTime(System.currentTimeMillis());
	// data.setUid(uid);
	// data.setVid(videoData.getVideoId());
	// return data;
	// }

	public static String getDownloadRootPath(String name) {
		return Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/" + name;
	}
}
